package com.example.demo.controller;

import com.example.demo.entity.TestAnswer;
import com.example.demo.repository.MbtiAnswerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/mbti-answers")
@CrossOrigin
public class MbtiAnswerController {

    @Autowired
    private MbtiAnswerRepository mbtiAnswerRepository;

    // 获取所有答案
    @GetMapping
    public List<TestAnswer> getAllAnswers() {
        return mbtiAnswerRepository.findAll();
    }

    // 根据TestRecord的id获取所有答案
    @GetMapping("/test-record/{testRecordId}")
    public List<TestAnswer> getAnswersByTestRecord(@PathVariable Long testRecordId) {
        return mbtiAnswerRepository.findByTestRecordId(testRecordId);
    }

    // 根据MbtiQuestion的id获取所有答案
    @GetMapping("/question/{questionId}")
    public List<TestAnswer> getAnswersByQuestion(@PathVariable Long questionId) {
        return mbtiAnswerRepository.findByQuestionId(questionId);
    }

    // 提交一个新的答案
    @PostMapping
    public ResponseEntity<TestAnswer> createAnswer(@RequestBody TestAnswer testAnswer) {
        TestAnswer savedAnswer = mbtiAnswerRepository.save(testAnswer);
        return ResponseEntity.ok(savedAnswer);
    }

    // 更新一个现有的答案
    @PutMapping("/{id}")
    public ResponseEntity<TestAnswer> updateAnswer(@PathVariable Long id, @RequestBody TestAnswer testAnswer) {
        if (!mbtiAnswerRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }

        testAnswer.setId(id);
        TestAnswer updatedAnswer = mbtiAnswerRepository.save(testAnswer);
        return ResponseEntity.ok(updatedAnswer);
    }

    // 删除一个答案
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteAnswer(@PathVariable Long id) {
        if (!mbtiAnswerRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }

        mbtiAnswerRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}
